package net.qiqbframework.eventhandling;

import net.qiqbframework.messaging.GenericMessage;
import net.qiqbframework.messaging.Message;
import net.qiqbframework.messaging.MessageDecorator;
import net.qiqbframework.messaging.MetaData;
import net.qiqbframework.serialization.CachingSupplier;

import javax.annotation.Nonnull;
import java.time.Clock;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class GenericEventMessage<T> extends MessageDecorator<T> implements EventMessage<T> {

    private final Supplier<Instant> timestampSupplier;

    /**
     * {@link Clock} instance used to set the time on new events. To fix the time while testing set this value to a
     * constant value.
     */
    public static Clock clock = Clock.systemUTC();

    /**
     * Returns the given event as an EventMessage. If {@code event} already implements EventMessage, it is
     * returned as-is. If it is a Message, a new EventMessage will be created using the payload and meta data of the
     * given message. Otherwise, the given {@code event} is wrapped into a GenericEventMessage as its payload.
     *
     * @param event the event to wrap as EventMessage
     * @param <T>   The generic type of the expected payload of the resulting object
     * @return an EventMessage containing given {@code event} as payload, or {@code event} if it already implements
     * EventMessage.
     */
    @SuppressWarnings("unchecked")
    public static <T> EventMessage<T> asEventMessage(@Nonnull Object event) {
        if (EventMessage.class.isInstance(event)) {
            return (EventMessage<T>) event;
        } else if (event instanceof Message) {
            Message<T> message = (Message<T>) event;
            return new GenericEventMessage<>(message, clock.instant());
        }
        return new GenericEventMessage<>(new GenericMessage<>((T) event), clock.instant());
    }

    /**
     * Creates a GenericEventMessage with given {@code payload}, and an empty MetaData.
     *
     * @param payload The payload for the message
     * @see #asEventMessage(Object)
     */
    public GenericEventMessage(T payload) {
        this(payload, MetaData.emptyInstance());
    }

    /**
     * Creates a GenericEventMessage with given {@code payload} and given {@code metaData}.
     *
     * @param payload  The payload of the EventMessage
     * @param metaData The MetaData for the EventMessage
     * @see #asEventMessage(Object)
     */
    public GenericEventMessage(T payload, @Nonnull Map<String, ?> metaData) {
        this(new GenericMessage<>(payload, metaData), clock.instant());
    }

    /**
     * Constructor to reconstruct an EventMessage using existing data.
     *
     * @param identifier The identifier of the Message
     * @param timestamp  The timestamp of the Message creation
     * @param payload    The payload of the message
     * @param metaData   The metadata of the message
     */
    public GenericEventMessage(@Nonnull String identifier, T payload, @Nonnull Map<String, ?> metaData,
                               @Nonnull Instant timestamp) {
        this(new GenericMessage<>(identifier, payload, metaData), timestamp);
    }

    /**
     * Constructor to reconstruct an EventMessage using existing data. The timestamp of the event is supplied lazily to
     * prevent unnecessary deserialization of the timestamp.
     *
     * @param delegate          The message containing payload, identifier and metadata
     * @param timestampSupplier Supplier for the timestamp of the Message creation
     */
    public GenericEventMessage(@Nonnull Message<T> delegate, @Nonnull Supplier<Instant> timestampSupplier) {
        super(delegate);
        this.timestampSupplier = CachingSupplier.of(timestampSupplier);
    }

    /**
     * Initializes a {@link GenericEventMessage} with given message as delegate and given {@code timestamp}. The given
     * message will be used supply the payload, metadata and identifier of the resulting event message.
     *
     * @param delegate  the message that will be used as delegate
     * @param timestamp the timestamp of the resulting event message
     */
    protected GenericEventMessage(@Nonnull Message<T> delegate, @Nonnull Instant timestamp) {
        this(delegate, CachingSupplier.of(timestamp));
    }

    @Nonnull
    @Override
    public Instant getTimestamp() {
        return timestampSupplier.get();
    }

    @Override
    public Collection<String> supportHandlerUrl() {
        return List.of();
    }



    @Override
    public boolean isScout() {
        return false;
    }

    @Override
    protected void describeTo(StringBuilder stringBuilder) {
        super.describeTo(stringBuilder);
        stringBuilder.append(", timestamp='").append(getTimestamp());
    }

    @Override
    protected String describeType() {
        return "GenericEventMessage";
    }
}
